package sk.stuba.fiit.clientApp.service.impl;

import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
import java.security.cert.X509Certificate;
import java.util.List;

import org.springframework.stereotype.Service;

import sk.stuba.fiit.clientApp.service.CryptographyService;

@Service("cryptographyService")
public class CryptographyServiceImpl implements CryptographyService{
	

	@Override
	public byte[] calculateSignatureFromHashData(String algorithm,PrivateKey privateKey,List<Object>data) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException{
		byte[] signatureValue;
		Signature signature = Signature.getInstance(algorithm, "BC");	
		SecureRandom random = new SecureRandom();
		byte[] bytes = new byte[1024/8];
		random.nextBytes(bytes);
		signature.initSign(privateKey, random);
		for(int i = 0; i<data.size(); i++){
			byte[]tmp = (byte[]) data.get(i);
			signature.update(tmp);
		}
		signatureValue = signature.sign();
		return signatureValue;
	}
	
	@Override
	public boolean verifieSignature(String algorithm, X509Certificate certificate,List<Object>data, byte[] signatureValue) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException{
		if(algorithm.split("#").length > 1){
            algorithm = algorithm.split("#")[1].split("-")[0];
    }
		Signature signature = Signature.getInstance(algorithm);
		signature.initVerify(certificate);
		for(int i = 0; i<data.size();i++){
			byte[] tmp =  (byte[]) data.get(i);
			signature.update(tmp);
		}
		if(signature.verify(signatureValue)){
			return true;
		}else{
			return false;
		}
	}
	
	 public byte[] calculateHash(byte[] data,String algorithm) throws NoSuchAlgorithmException{
         if(algorithm.split("#").length > 1){
                 algorithm = algorithm.split("#")[1];
         }
         MessageDigest ms = MessageDigest.getInstance(algorithm);
                 ms.update(data);
                 return ms.digest();
 }

}
